import React, { useEffect, useState } from 'react'
import { Card, Descriptions, Progress, message, Tag, Drawer, Statistic, Affix, Button, Modal, Form, Input, Spin } from 'antd';
import styles from './style.less'
import { getStudentCourse, getStudentTest, getTestQuestion, addResult, getScore, getAnswer } from './service'
import ProTable from '@ant-design/pro-table';
import MPageContainer from '@/components/MPageContainer';
import Judge from './components/Judge';
import Choice from './components/Choice';
import Blanks from './components/Blanks';
import Program from './components/Program';
import qs from 'qs'

const Center: React.FC = () => {

    const [courseInfo, setCourseInfo] = useState();
    const [tableData, setTableData] = useState({});
    const [visible, setVisible] = useState(false)
    const [questions, setQuestions] = useState([])
    const [durationTime, setDurationTime] = useState()
    const [testName, setTestName] = useState('')
    const [questionResults, setQuestionResults] = useState<any>([])
    const [testType, setTestType] = useState(1)
    const [deadTime, setDeadTime] = useState<any>()
    const [disabled, setDisabled] = useState(false)
    const [saveLoading, setSaveLoading] = useState(false)
    const [scoreLoading, setScoreLoading] = useState(true)
    const [answerLoading, setAnswerLoading] = useState(true)
    const [scoreVisvible, setScoreVisvible] = useState(false)
    const [answerVisvible, setAnswerVisvible] = useState(false)
    const [score, setScore] = useState<any>()
    const [testId, setTestId] = useState()
    const [answer, setAnswer] = useState<any>([])


    const info: any = localStorage.getItem('info')
    const showInfo = JSON.parse(info);
    const studentId = showInfo.studentId;


    const { Countdown } = Statistic;
    // const { Item } = Form;

    // const formLayout = {
    //     labelCol: { span: 4 },
    //     wrapperCol: { span: 18 },
    // };

    // const [scoreForm] = Form.useForm();

    const getCourse = async () => {
        const res = await getStudentCourse(studentId)
        setCourseInfo(res.data)
    }


    useEffect(() => {
        getCourse()
    }, [])

    const setDeadline = (endTime: string | number | Date) => {
        const end: any = new Date(endTime)
        const now: any = new Date()
        const time = Date.now() + (end - now);
        setDeadTime(time)
    }

    // useEffect(() => {
    //     console.log(deadTime, 'deadTimedeadTime');
    // })

    const enterTest = async (record: any) => {
        const res = await getTestQuestion(record.testId)
        const length = res.data.length;
        let arr: any[] = []

        // for (let i = 0; i < length; i++) {
        //     arr.push('')
        // }
        res.data.forEach((item: { questionId: any; }) => {
            arr.push({ questionId: item.questionId, result: "", testId: testId })
        })
        if (record.isFinished === 0) {
            setDisabled(false)
        } else {
            setDisabled(true)
        }
        console.log(arr, 'arr');
        setDeadline(record.endTime)
        setTestName(record.testName)
        setQuestionResults(arr)
        setQuestions(res.data)
        setTestType(record.type)
        setTestId(record.testId)
        setVisible(true)
    }


    const onExpand = (expanded: boolean, record: any) => {
        const getTestList = async () => {
            const res = await getStudentTest(record.courseId)
            setTableData({
                ...tableData,
                [record.courseId]: res.data
            })
        }
        if (expanded) {
            getTestList()
        }
    }

    const expandedRowRender = (record: any) => {
        return (
            <>
                <ProTable
                    headerTitle={'测验列表'}
                    columns={[
                        {
                            title: '类型',
                            dataIndex: 'type',
                            render: (text: any, record: any) => {
                                return <Tag color={text === 1 ? 'yellow' : 'green'}>{text === 1 ? '测验' : '考试'}</Tag>
                            },
                        },
                        { title: '测验名称', dataIndex: 'testName' },
                        { title: '开始时间', dataIndex: 'startTime' },
                        { title: '结束时间', dataIndex: 'endTime' },
                        {
                            title: '持续时间',
                            dataIndex: 'durationTime',
                            render: (text: any, record: any) => {
                                const start: any = new Date(record.startTime)
                                const end: any = new Date(record.endTime)
                                const time = Math.floor((end - start) / 1000 / 60)
                                return `${time} 分钟`
                            },
                        },
                        {
                            title: '完成状态',
                            dataIndex: 'isFinished',
                            render: (text: any, record: any) => {
                                return <Tag color={text === 0 ? 'red' : 'green'}>{text === 0 ? '未完成' : '已完成'}</Tag>
                            },
                        },
                        {
                            title: '操作',
                            dataIndex: 'operation',
                            render: (_: any, record: any) => {
                                return <>
                                    <a onClick={() => enterTest(record)}>进入</a>
                                </>
                            }
                        },
                    ]}
                    key='testId'
                    search={false}
                    options={false}
                    dataSource={tableData[record.courseId]}
                    // pagination={false}
                    pagination={{
                        showQuickJumper: true,
                    }}
                />
            </>
        );
    };

    const onCancel = () => {
        setVisible(false)
    }

    const onFinish = () => {
        message.warning('考试结束，请提交答卷,一分钟后将不能提交！')
        setTimeout(() => {
            setDisabled(true)
        }, 60000)
    }

    // const changeResult = (val: any) => {
    //     console.log(val, 'valvalval');
    //     setQuestionResults(val)
    // }


    const columns = [
        {
            title: '课程名字',
            dataIndex: 'courseName',
        },
        {
            title: '课程简介',
            dataIndex: 'courseContent',
        },
        {
            title: '课程开始时间',
            dataIndex: 'startTime',
        },
        {
            title: '课程结束时间',
            dataIndex: 'endTime',
        },
        {
            title: '完成状态',
            dataIndex: 'isFinished',
            render: (text: any, record: any) => {
                return <Tag color={text === 0 ? 'red' : 'green'}>{text === 0 ? '未完成' : '已完成'}</Tag>
            },
        },
    ]

    const handleSubmit = async () => {
        const obj = { questionResults: JSON.stringify(questionResults) }
        const res = await addResult(qs.stringify(obj))
        if (res.code === 200) {
            setSaveLoading(false);
            setDisabled(true)
            setScoreVisvible(true)
        }
        setScoreLoading(true)
        const result: any = await getScore(studentId, testId)
        if (result.code === 200) {
            setScore(result.data.scoreValue)
        }
        setScoreLoading(false)
    }

    const handleScoreCancel = () => {
        setScoreVisvible(false)
    }

    const handleCheckScore = async () => {
        setScoreVisvible(true)
        setScoreLoading(true)
        const result: any = await getScore(studentId, testId)
        if (result.code === 200) {
            setScoreLoading(false)
            setScore(result.data.scoreValue || 0)
        }
    }

    const renderFooter = () => {
        return (
            <div style={{ textAlign: 'right' }}>
                <Button
                    style={{ marginRight: 8 }}
                    type="primary"
                    loading={saveLoading}
                    onClick={handleSubmit}
                    disabled={disabled}
                >
                    提交答案
              </Button>
                {disabled == true && <Button
                    style={{ marginRight: 8 }}
                    type="primary"
                    // loading={saveLoading}
                    onClick={handleCheckAnswer}
                >
                    查看答案
              </Button>}
                {disabled == true && <Button
                    style={{ marginRight: 8 }}
                    type="primary"
                    // loading={saveLoading}
                    onClick={handleCheckScore}
                >
                    查看分数
              </Button>}
            </div>
        );
    }

    const handleCheckAnswer = async () => {
        setScoreVisvible(false)
        setAnswerVisvible(true)
        setAnswerLoading(true)
        const res = await getAnswer(testId)
        if (res.code === 200) {
            const answer: any[] = []
            res.data.forEach((item: any) => {
                // if (item.type === 1) {
                //     answer.push(<pre>{item.answer}</pre>)
                // } else {
                answer.push(item.answer)
                // }
            })
            setAnswer(answer)
            setAnswerLoading(false)
        }
    }

    const handleAnswerCancel = () => {
        setAnswerVisvible(false)
    }

    const renderScoreFooter = () => {
        return (
            <div style={{ textAlign: 'right' }}>
                <Button
                    style={{ marginRight: 8 }}
                    type="primary"
                    // loading={saveLoading}
                    onClick={handleCheckAnswer}
                >
                    查看答案
              </Button>
            </div>
        );
    }


    return (
        <>
            <MPageContainer>
                <Card className={styles.card}>
                    <ProTable
                        headerTitle={<div className={styles.tag}><Tag color={'blue'}>课程信息</Tag></div>}
                        columns={columns}
                        dataSource={courseInfo}
                        toolBarRender={() => []}
                        search={false}
                        rowKey="courseId"
                        key="courseId"
                        pagination={{
                            showQuickJumper: true,
                        }}
                        expandable={{ expandedRowRender, onExpand }}
                    />
                </Card>
            </MPageContainer>
            <Drawer
                title={testType === 1 ? '测验' : '考试'}
                visible={visible}
                onClose={onCancel}
                width="100%"
                bodyStyle={{
                    background: '#f0f0f0'
                }}
                footer={renderFooter()}
                className={styles.main}>
                <Affix offsetTop={55.1}>
                    <div className={styles.countDown}><Countdown value={deadTime} onFinish={onFinish} /></div>
                </Affix>
                {/* <Card>{testName}</Card> */}
                {
                    questions.map((item: any, index) => {
                        if (item.type === 1) {
                            return <Program
                                data={item}
                                idx={index}
                                questionResults={questionResults}
                                testId={testId}
                                studentId={studentId}
                            />
                        }
                        else if (item.type === 2) {
                            return <Judge
                                data={item}
                                idx={index}
                                questionResults={questionResults}
                                testId={testId}
                                studentId={studentId}
                            />
                        } else if (item.type === 3) {
                            return <Choice
                                data={item}
                                idx={index}
                                questionResults={questionResults}
                                testId={testId}
                                studentId={studentId}
                            />
                        } else if (item.type === 4) {
                            return <Blanks
                                data={item}
                                idx={index}
                                questionResults={questionResults}
                                testId={testId}
                                studentId={studentId}
                            />
                        }
                        return ''
                    })
                }
            </Drawer>
            <Modal title="分数" visible={scoreVisvible} footer={renderScoreFooter()} onCancel={handleScoreCancel} className={styles.score}>
                <Spin spinning={scoreLoading}>
                    {scoreLoading ? '' : <Progress type="circle" percent={parseInt(score)} format={percent => `${percent} 分`} />}
                    {/* {scoreLoading ? '' : <Progress type="circle" percent={90} />} */}

                </Spin>
            </Modal>
            <Modal title="答案" visible={answerVisvible} onCancel={handleAnswerCancel} onOk={handleAnswerCancel} width={'60%'} className={styles.answerList}>
                <Spin spinning={answerLoading}>
                    {answer.map((item: any, index: any) => {
                        if (item.includes('\n')) {
                            return <li className={styles.list}>{index + 1}、<pre>{item}</pre></li>
                        } else {
                            return <li className={styles.list}>{`${index + 1}、${item}`}</li>
                        }
                    })}
                </Spin>
            </Modal>
        </>
    );
}

export default Center;
